import axios from 'axios'
// import { ERR_OK } from '@/api/apiConst'
import request from '@/utils/request'
import Cookie from 'js-cookie'
import moment from 'moment'
import {getToken} from '@/utils/auth'
import qs from 'qs'
import {getLodop} from '@/views/productManagement/assets/LodopFuncs'

export const ERR_OK = 1 //  成功的状态码

/**
 *
 * @param num 要补充0的值
 * @param bit 需要总位数
 * @returns {string}
 */
export function paddingTime(num, bit) {
  let string = String(num)
  let length = string.length
  while (length < bit) {
    length++
    string = '0' + string
  }
  return string
}

/**
 * 获取指定范围的整数随机数
 * @param min
 * @param max
 * @returns {number}
 */
export function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

// //  通过函数科里化把url参数固化
// export const get = (url) => (params) => {
//   return axios.get(url, {
//     params
//   }).then(({ data }) => {
//     const { errno } = data
//     if (ERR_OK === errno) {
//       //   return data
//       return Promise.resolve(data)
//     } else {
//       //权限不够... 未登录... 等其他错误码给予不同的返回
//       return Promise.reject(data)
//     }
//   }).catch(reason => console.log('请求失败,请检查网络___   ' + reason))
// }

export const isObject = (value) => {
  return Object.prototype.toString.apply(value) === '[object Object]'
}

export const tokenRequest = (sessionKey = 'userName') => ({url, method, params, data}) => {
  return request({
    url, method, params: {...Object.assign({}, {token: Cookie.get(sessionKey)}, params)}, data
  })
}

export const deleteNullValue = (obj) => {
  if (!(typeof obj == 'object')) {
    return
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] === undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

export const getLabelByVal = (enumArr) => (val, retAttrName = 'label') => {
  const ret = enumArr.find(e => {
    return parseInt(e.value) === parseInt(val)
  })
  if (ret) {
    return ret[retAttrName]
  }
  return ''
}

export const getValByLabel = (enumArr) => (label, retAttrVal = 'value') => {
  const ret = enumArr.find((e) => {
    return label.trim() === e.label
  })
  if (ret) {
    return +ret[retAttrVal]
  }
  return ''
}

export function dateFormat(time) {
  if (!time) {
    return
  }
  let day = moment(new Date(time))
  return day.format('YYYY-MM-DD HH:mm:ss')
}

/**
 *  枚举获取方法
 * 可以全部不传,这样你的数据中的就必须按照 engName chName这两个key来定义
 * @param formColDir 字典
 * example Array : [{engName:"user",chName:"用户"},{engName:"role",chName:"角色"},{engName:"authority",chName:"权限"}]
 *
 * @param code  default chName
 * @param name  default engName
 *
 * @returns {Function}
 */
// export const getChNameByEngName = ({ colDir, code = 'code', name = 'name', isShowWarn = true } = {}) => (engName) => {
//   if (!colDir) {
//     throw new Error('列 dictionary 不存在! 请检查传入参数--- chino')
//   }
//   const matches = colDir.filter((e) => {
//     return e[code] === engName
//   })
//   if (matches.length) {
//     return matches[0][name]
//   }
//   isShowWarn && console.warn(`转换列失败,列名 "${engName}" 不存在于对象中!`)
//   return engName
// }

/**
 *
 * @param strList
 * @param attrName
 * @param splitSymbol
 * @returns {*}
 */
export const list2stringWithSplitSymbol = (strList, attrName, splitSymbol = ',') => strList.map(e => e[attrName]).join(splitSymbol)

export const openNewPage = function (vm, {name = 'BlackPage', query} = {}) {
  const {href} = vm.$router.resolve({name, query})
  window.open(href, '_blank')
}

//  导出账单  2 excel
export function exportExcel({url, data, formDataFunc}) {
  const _data = qs.stringify(deleteNullValue(data))
  //  example url => /order/exportConsumeOrderList
  return axios.post(`${process.env.BASE_API}${url}`, _data, {
    headers: {
      'X-Token': getToken()
    },
    timeout: 360 * 1000,  //  360秒过期超时
    withCredentials: true,// 允许携带cookie    前后端分离
    responseType: 'arraybuffer'
    // 'responseType': 'blob'  //设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置！！！
  }).then((res) => {
    const fileName = '账单详细.xls'
    const blob = new Blob([res.data], {type: 'application/x-xls'})
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, fileName)
    } else {
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
      link.click()
      window.URL.revokeObjectURL(link.href)
    }

  }).catch((error) => {
    console.log(error)
  })

}

/**
 * 重量单位换算
 * @param num 数量
 * @param curUnit 原单位
 * @param toUnit 目标单位
 * @return {string}
 * @constructor
 */
export const getNumByUnit = function (num, curUnit, toUnit) {
  if (curUnit === toUnit) {
    return num
  }
  const fRate = {//换算率
    ng: {
      μg: 0.001,
      mg: 0.001 * 0.001,
      g: 0.001 * 0.001 * 0.001,
      kg: 0.001 * 0.001 * 0.001 * 0.001,
      t: 0.001 * 0.001 * 0.001 * 0.001 * 0.001,
      ul: 0.001 * 0.001,
      ml: 0.001 * 0.001 * 0.001,
      L: 0.001 * 0.001 * 0.001 * 0.001
    },
    μg: {
      ng: 1000,
      mg: 0.001,
      g: 0.001 * 0.001,
      kg: 0.001 * 0.001 * 0.001,
      t: 0.001 * 0.001 * 0.001 * 0.001,
      ul: 0.001,
      ml: 0.001 * 0.001,
      L: 0.001 * 0.001 * 0.001
    },
    mg: {
      ng: 1000 * 1000,
      μg: 1000,
      g: 0.001,
      kg: 0.001 * 0.001,
      t: 0.001 * 0.001 * 0.001,
      ul: 1,
      ml: 0.001,
      L: 0.001 * 0.001
    },
    g: {ng: 1000 * 1000 * 1000, μg: 1000 * 1000, mg: 1000, kg: 0.001, t: 0.001 * 0.001, ul: 1000, ml: 1, L: 0.001},
    kg: {
      ng: 1000 * 1000 * 1000 * 1000,
      μg: 1000 * 1000,
      mg: 1000,
      g: 1000,
      t: 0.001,
      ul: 1000 * 1000,
      ml: 1000,
      L: 1
    },
    t: {
      ng: 1000 * 1000 * 1000 * 1000 * 1000,
      μg: 1000 * 1000 * 1000,
      mg: 1000 * 1000,
      g: 1000 * 1000,
      kg: 1000,
      ul: 1000 * 1000 * 1000,
      ml: 1000 * 1000,
      L: 1000
    },
    // ml: { ng: 1000 * 1000 * 1000, μg: 1000 * 1000, mg: 1000, g: 1, kg: 0.001, t: 0.001 * 0.001, ul: 1000 , L: 0.001 },
    // ul: { ng: 1000 * 1000, μg: 1000, ml: 1, g: 0.001, kg: 0.001 * 0.001, t: 0.001 * 0.001 * 0.001, ml: 0.001, L: 0.001 * 0.001 },
    L: {
      ng: 1000 * 1000 * 1000 * 1000,
      μg: 1000 * 1000,
      mg: 1000,
      g: 1000,
      kg: 1,
      t: 0.001,
      ul: 1000 * 1000,
      ml: 1000
    }
  }
  const tnum = (num * fRate[curUnit][toUnit]).toFixed(2)
  return tnum
}

export const printAllPdf = (ReportList, {PrinterNameProp = 'PrinterName', streamStrProp = 'Context'}={}) => {
  ReportList.filter(v => v).forEach(({
                                       [PrinterNameProp]: PrinterName,
                                       [streamStrProp]: Context
                                     }={}) => printPdf(Context, PrinterName))
}

export const printPdf = (content, printerName, cb) => {
  const LODOP = getLodop()

  LODOP.On_Return = cb

  if (content === '' || !content) {
    return
  }

  LODOP['ADD_PRINT_PDF'](0, 0, '100%', '100%', content)
  LODOP['SET_PRINT_STYLEA'](0, 'PDFScalMode', 1)
  LODOP['SET_PRINT_PAGESIZE'](3, 0, 0, '') // (1, width, height)

  LODOP['SET_PRINTER_INDEX'](printerName)
  LODOP['PRINT']()
}

window.printPdf = printPdf
